package com.adaptiveAgingAdmin.security.manager;

import com.adaptiveAgingAdmin.domain.Admin;
import com.adaptiveAgingAdmin.domain.Menu;
import com.adaptiveAgingAdmin.mapper.MenuMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 动态权限检测
 *
 * @author 张涛
 */
@Component
public class RoleAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public void verify(Supplier<Authentication> authentication, RequestAuthorizationContext requestAuthorizationContext) {
        AuthorizationManager.super.verify(authentication, requestAuthorizationContext);
    }
    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext authorizationContext) {
        String requestURI = authorizationContext.getRequest().getRequestURI();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type",2);
        queryWrapper.eq("url",requestURI);
        List<Menu> menus=menuMapper.selectList(queryWrapper);
        List<String> perms = menus.stream().map(Menu::getPerm).distinct().collect(Collectors.toList());
        Admin admin=(Admin) authentication.get().getPrincipal();
        List<String> auths = admin.getMenus().stream().map(Menu::getPerm).distinct().collect(Collectors.toList());
        for (String auth:auths){
            if(perms.contains(auth)){
                return new AuthorizationDecision(true);
            }
        }
        throw new AccessDeniedException("对不起，您没有访问\""+requestURI+"\"的权限");
    }
}
